package com.py.gs.businese.unionbattletest;

import java.util.Iterator;

/**
 * 500, 50, 10000
 * 循环跑10次battle
 * 
10次总耗时:350~450ms
10次总对战次数:45047199
 * 
 * @author cyd
 * @date 2018年4月19日
 */
public class UnionBattleService1 extends UnionBattleService {
	
	public UnionBattleService1(int unionNum, int ministerNum, int powerBound) {
		super(unionNum, ministerNum, powerBound);
	}
	
	protected boolean battle(UnionBattleInfo attack, UnionBattleInfo defend) {
		Iterator<MinisterBattleInfo> attackIt = attack.ministers.iterator();
		Iterator<MinisterBattleInfo> defendIt = defend.ministers.iterator();
		if (!attackIt.hasNext()) {
			return false;
		}
		if (!defendIt.hasNext()) {
			return true;
		}
		MinisterBattleInfo attackMinister = attackIt.next();
		MinisterBattleInfo defendMinister = defendIt.next();
		while (true) {//打到自己活着对方没有出战大臣，停止战斗返回战斗结果
			int battleRet = battle(attackMinister, defendMinister);
			if (battleRet < 0) {//攻击方输
				attackMinister.resetPower();
				if (!attackIt.hasNext()) {
					defendMinister.resetPower();
					return false;
				}
				if (defendMinister.ministerWinCount < 2) {
					defendMinister.ministerWinCount++;
				} else {
					defendMinister.resetPower();
					if (!defendIt.hasNext()) {
						return true;
					}
					defendMinister = defendIt.next();
				}
				attackMinister = attackIt.next();
			} else if (battleRet > 0) {//防守方输
				defendMinister.resetPower();
				if (!defendIt.hasNext()) {
					attackMinister.resetPower();
					return true;
				}
				if (attackMinister.ministerWinCount < 2) {
					attackMinister.ministerWinCount++;
				} else {
					attackMinister.resetPower();
					if (!attackIt.hasNext()) {
						return false;
					}
					attackMinister = attackIt.next();
				}
				defendMinister = defendIt.next();
			} else {
				attackMinister.resetPower();
				defendMinister.resetPower();
				if (!attackIt.hasNext()) {
					return false;
				}
				if (!defendIt.hasNext()) {
					return true;
				}
				attackMinister = attackIt.next();
				defendMinister = defendIt.next();
			}
		}
	}
	/**
	 * 大臣战斗结果，小于0表示输，大于0表示赢，等于0表示一起死
	 * @param attackMinister
	 * @param defendMinister
	 * @return
	 */
	private int battle(MinisterBattleInfo attackMinister, MinisterBattleInfo defendMinister) {
		battleCount++;
		if (attackMinister.ministerLeftPower > defendMinister.ministerLeftPower) {
			attackMinister.ministerLeftPower -= defendMinister.ministerLeftPower;
			return 1;
		} else if (attackMinister.ministerLeftPower < defendMinister.ministerLeftPower) {
			defendMinister.ministerLeftPower -= attackMinister.ministerLeftPower;
			return -1;
		} else {
			return 0;
		}
	}

}
